using System;
using System.Collections.Generic;
using System.Text;

namespace RapidHDL.Fabric
{
    public class ROMBlock : Block
    {
        int iWidth;
        int iDepth;

        Dictionary<int, int> dicValues = new Dictionary<int, int>();

        public ROMBlock(string psName, int piWidth, int piDepth)
            : base(psName,"ROM")
        {
            iWidth = piWidth;
            iDepth = piDepth;
            this.CreateInput("ADDRESS", Conversion.MinBitWidth(piDepth));
            this.CreateOutput("DATA", piWidth);
        }

        internal override void GenerateStructure()
        {
            ROM oRom = new ROM(ParentComponent, "ram_" + sName,iWidth,iDepth);

            oRom.AddTable(dicValues);

            Inputs["ADDRESS"].LinkNodeVector(oRom.I_Address);
            Outputs["DATA"].LinkNodeVector(oRom.O_Value);
        }

        public int AddValue(int piValue, bool pbCompact)
        {
            if (pbCompact)
            {
                foreach (int iAddress in dicValues.Keys)
                {
                    if (piValue == dicValues[iAddress])
                        return iAddress;
                }
            }

            dicValues.Add(dicValues.Count, piValue);
            if (dicValues.Count == iDepth)
                ReportError("More than " + iDepth.ToString() + " values stored in ROM.");
            return dicValues.Count - 1;
        }
    }
}
